package com.primi.chen;

import com.primi.chen.zookeeper.NodeDiscovery;
import com.primi.chen.zookeeper.ServiceConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.util.Random;
import java.util.concurrent.*;

/**
 * Create AT 2019/12/25 14:36:14:36
 *
 * @author Primi.Chen(Chenxiangxu)
 */

@Slf4j
public class DemoServerExecuter {

    @Test
    public void main() throws InterruptedException {
        int thread = 2;
        CountDownLatch countDownLatch = new CountDownLatch(thread);
        ScheduledThreadPoolExecutor executorService = new ScheduledThreadPoolExecutor(10);
        for (int i = 0; i < thread; i++) {
            NodeDiscovery nodeDiscovery = NodeDiscovery.of(configuration(i));
            nodeDiscovery.setCloseListener(()->{
                countDownLatch.countDown();
                System.out.println("Current: " + countDownLatch.getCount());
            });
            executorService.schedule(nodeDiscovery,1L,TimeUnit.MICROSECONDS);
            int delayClose = new Random().nextInt(5) + 5;
            log.info("Delay: {} , {}",delayClose,nodeDiscovery.getConfiguration().filename());
            executorService.schedule(nodeDiscovery::close,delayClose,TimeUnit.SECONDS);
        }
        countDownLatch.await();
        executorService.shutdown();
    }

    public ServiceConfiguration configuration(int port) {
        ServiceConfiguration configuration = new ServiceConfiguration();
        configuration.setName("demo-server-executer");
        configuration.setHost("127.0.0.1");
        configuration.setPort(8000 + port);
        configuration.setSessionTimeout(5000);
        configuration.setZkservers("127.0.0.1:2181");
        configuration.setVersion("1.0");
        return configuration;
    }
}
